﻿using DoNet.System.IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace DoNet.Extensions.Mvc
{
    /// <summary>
    /// WebApi控制器基类
    /// </summary>
    [ApiController]
    [EnableCors("Cors")]
    public class BaseApiController : Controller
    {
        /// <summary>
        /// 当前登录的用户属性
        /// </summary>
        public CurrentUser CurrentUser;

        /// <summary>
        /// 
        /// </summary>
        private readonly ILogger logger;
        /// <summary>
        /// 
        /// </summary>
        private readonly ITokenService tokenService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        public BaseApiController(ILogger<BaseApiController> _logger, ITokenService _tokenService)
        {
            logger = _logger;
            tokenService = _tokenService;
        }

        #region 
        /// <summary>
        /// 重写基类在Action执行之前的事情
        /// 根据token获得当前用户，允许匿名的不需要获取用户
        /// </summary>
        /// <param name="context">重写方法的参数</param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                //匿名访问，不需要token认证、签名和登录
                var allowanyone = controllerActionDescriptor?.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), true);
                if (allowanyone != null) return;

                //需要token认证
                if (context.HttpContext.Request.Headers.TryGetValue("Authorization", out var authorizationValue))
                {
                    //authorizationValue 现在包含了 "Authorization" 头部的值
                    Console.WriteLine(authorizationValue);
                    //可以进一步处理authorizationValue，例如解析令牌等

                    var authorization = authorizationValue.FirstOrDefault() ?? string.Empty;
                    if (authorization.StartsWith("Bearer ", StringComparison.Ordinal))
                    {

                        string token = authorization.Substring(7);
                        bool isValidate = tokenService.ValidateToken(token);
                        //token验证失败
                        if (!isValidate)
                        {
                            context.Result = new UnauthorizedObjectResult("无效的凭证！");
                        }
                        return;
                    }
                }
                else
                {
                    // "Authorization" 头部不存在
                    //Console.WriteLine("Authorization header is missing.");
                    context.Result = new UnauthorizedObjectResult("凭证缺失！");
                    return;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }
        }
        #endregion
    }
}
